package com.hrhx.springboot.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
 * @version 20150902
 * @author duhongming
 *
 */
//@Service
@SuppressWarnings("rawtypes")
public class PinyinUtil implements Comparator {
	
	//@Value("classpath:static/data/duoyinzi_pinyin.txt")
    private Resource info;
	/**
	 * 拼接拼音字符串
	 * @param pinyinArray
	 * @return
	 */
	private String concatPinyinStringArray(String[] pinyinArray) {
		StringBuffer pinyinStrBuf = new StringBuffer();
		if ((null != pinyinArray) && (pinyinArray.length > 0)) {
			for (int i = 0; i < pinyinArray.length; i++) {
				pinyinStrBuf.append(pinyinArray[i]);
			}
		}
		String outputString = pinyinStrBuf.toString();
		return outputString;
	}

	/**
	 * 比较字符串顺序
	 */
	@Override
	public int compare(Object o1, Object o2) {
		char c1 = ((String) o1).charAt(0);
		char c2 = ((String) o2).charAt(0);
		return concatPinyinStringArray(PinyinHelper
				.toHanyuPinyinStringArray(c1))
				.compareTo(concatPinyinStringArray(PinyinHelper
						.toHanyuPinyinStringArray(c2)));
	}
	/**
	 * 第一个全拼，剩余首拼
	 * @param input
	 * @return
	 */
	public static String getPinyinFirstCharExt(String input) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c <= 'ÿ') {
				sb.append(c);
			} else {
				String pinyin = null;
				try {
					HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
					format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
					format.setVCharType(HanyuPinyinVCharType.WITH_V);
					String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
					pinyin = pinyinArray[0];
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				} catch (NullPointerException e) {
					e.printStackTrace();
				}
				if (pinyin != null) {
					if(i==0){
						sb.append(pinyin);
					}else{
						sb.append(pinyin.charAt(0));
					}
					
				}
			}
		}
		return sb.toString();
	}

	///////////////////////////////////////java中将汉字转拼音,解决pinyin4j多音节问题///////////////////////////////////////////////
	private static final Logger logger = Logger.getLogger("devLog");  
    
    public static Map<String,String> dictionary = new HashMap<String,String>();  
  
    //加载多音字词典  
    public PinyinUtil(){  
          
	        BufferedReader br = null;  
	        try {
	            br = new BufferedReader(new InputStreamReader(info.getInputStream(),"UTF-8"));      
	            String line = null;  
	            while((line=br.readLine())!=null){  
	                  
	                String[] arr = line.split("#");  
	                  
	                if(StringUtils.isNotEmpty(arr[1])){  
	                    String[] sems = arr[1].split(" ");  
	                    for (String sem : sems) {  
	                          
	                        if(StringUtils.isNotEmpty(sem)){  
	                            dictionary.put(sem , arr[0]);  
	                        }  
	                    }  
	                }  
	            }  
	              
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }finally{  
	            if(br!=null){  
	                try {  
	                    br.close();  
	                } catch (IOException e) {  
	                    e.printStackTrace();  
	                }  
	            }  
	        }  
	  
	}  
      
    public static String[] chineseToPinYin(char chineseCharacter) throws BadHanyuPinyinOutputFormatCombination{  
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();  
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);  
        //ASCII >=33 ASCII<=125的直接返回 ,ASCII码表：http://www.asciitable.com/    
        if(chineseCharacter>=32 && chineseCharacter<=125){    
            return new String[]{String.valueOf(chineseCharacter)};  
        }  
          
        return PinyinHelper.toHanyuPinyinStringArray(chineseCharacter, outputFormat);  
    }  
      
    /** 
     * 获取汉字拼音的全拼 
     * @param chineseCharacter 
     * @return 
     * @throws BadHanyuPinyinOutputFormatCombination 
     */  
    public static String chineseToPinYinF(String chineseCharacter) throws BadHanyuPinyinOutputFormatCombination{  
        if(StringUtils.isEmpty(chineseCharacter)){  
            return null;  
        }  
          
        char[] chs = chineseCharacter.toCharArray();  
          
        StringBuilder result = new StringBuilder();  
          
        for(int i=0;i<chs.length;i++){  
            String[] arr = chineseToPinYin(chs[i]);  
            if(arr==null){  
                result.append("");  
            }else if(arr.length==1){  
                result.append(arr[0]);  
            }else if(arr[0].equals(arr[1])){  
                result.append(arr[0]);  
            }else{  
                  
                String prim = chineseCharacter.substring(i, i+1);  
//              System.out.println("prim="+prim+"**i="+i);  
                  
                String lst = null,rst = null;  
                  
                if(i<=chineseCharacter.length()-2){  
                    rst = chineseCharacter.substring(i,i+2);  
                }  
                if(i>=1 && i+1<=chineseCharacter.length()){  
                    lst = chineseCharacter.substring(i-1,i+1);  
                }  
                  
//              System.out.println("lst="+lst+"**rst="+rst);  
                  
                String answer = null;  
                for (String py : arr) {  
                      
                    if(StringUtils.isEmpty(py)){  
                        continue;  
                    }  
                      
                    if((lst!=null && py.equals(dictionary.get(lst))) ||  
                            (rst!=null && py.equals(dictionary.get(rst)))){  
                        answer = py;  
//                      System.out.println("get it,answer="+answer+",i="+i+"**break");  
                        break;  
                    }  
                      
                    if(py.equals(dictionary.get(prim))){  
                        answer = py;  
//                      System.out.println("get it,answer="+answer+",i="+i+"**prim="+prim);  
                    }  
                }  
                if(answer!=null){  
                    result.append(answer);  
                }else{  
                    logger.warn("no answer ch="+chs[i]);  
                }  
            }  
        }  
          
        return result.toString().toLowerCase();  
    }  
	/**
	 * 汉字转拼音（首字母）
	 * @param input
	 * @return
	 */  
    public static String chineseToPinYinS(String chineseCharacter) throws BadHanyuPinyinOutputFormatCombination{  
        if(StringUtils.isEmpty(chineseCharacter)){  
            return null;  
        }  
          
        char[] chs = chineseCharacter.toCharArray();  
          
        StringBuilder result = new StringBuilder();  
          
        for(int i=0;i<chs.length;i++){  
            String[] arr = chineseToPinYin(chs[i]);  
            if(arr==null){  
                result.append("");  
            }else if(arr.length==1){  
                result.append(arr[0].charAt(0));  
            }else if(arr[0].equals(arr[1])){  
                result.append(arr[0].charAt(0));  
            }else{  
                  
                String prim = chineseCharacter.substring(i, i+1);  
     //         System.out.println("prim="+prim+"**i="+i);  
                  
                String lst = null,rst = null;  
                  
                if(i<=chineseCharacter.length()-2){  
                    rst = chineseCharacter.substring(i,i+2);  
                }  
                if(i>=1 && i+1<=chineseCharacter.length()){  
                    lst = chineseCharacter.substring(i-1,i+1);  
                }  
                  
      //        System.out.println("lst="+lst+"**rst="+rst);  
                  
                String answer = null;  
                for (String py : arr) {  
                      
                    if(StringUtils.isEmpty(py)){  
                        continue;  
                    }  
                      
                    if((lst!=null && py.equals(dictionary.get(lst))) ||  
                            (rst!=null && py.equals(dictionary.get(rst)))){  
                        answer = py;  
                      System.out.println("get it,answer="+answer+",i="+i+"**break");  
                        break;  
                    }  
                      
                    if(py.equals(dictionary.get(prim))){  
                        answer = py;  
                     System.out.println("get it,answer="+answer+",i="+i+"**prim="+prim);  
                    }  
                }  
                if(answer!=null){  
                    result.append(answer.charAt(0));  
                }else{  
                    logger.warn("no answer ch="+chs[i]);  
                }  
            }  
        }  
          
        return result.toString().toLowerCase();  
    }  
          
//	public static void main(String[] args) throws Exception {
//		
//		String[] data = { "孙", "孟", "宋", "尹", "廖", "张三", "蚪", "窦鸿槟", "徐", "昆","曹", "曾", "怡", "a", "。"};
//		
//		List list = Arrays.asList(data);
//		Arrays.sort(data, new PinyinUtil());
//		System.out.println("汉字排序："+list);
//	
//	}
}